#ifndef __THREAD_HPP__
#define __THREAD_HPP__
#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>

using namespace std;

template <class T>
using func_t = function<void(T&)>;

namespace thread_ns
{
    template <class T>

    class Thread
    {
        void Excute()
        {
            _func(_data);
        }

    public:
        Thread(func_t<T> func, T &data, const string &name)
            : _func(func), _data(data), _threadname(name), _stop(true)//
        {
        }

        static void *runthread(void *args)
        {
            Thread<T> *self = static_cast<Thread<T> *>(args);
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, runthread, this);
            if (!n)
            {
                _stop = false;
                return true;
            }
            else
                return false;
        }

        void Stop()
        {
            _stop = true;
        }

        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        string getName()
        {
            return _threadname;
        }

        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        string _threadname;
        func_t<T> _func;
        bool _stop;
        T &_data;
    };
}

#endif